package com.joshua.spring.integration.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.entity.vo.GlobalResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * com.joshua.spring.business.integration.exception -- IntegrationAuthenticationEntryPoint
 * description:
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/1/14 9:03
 */
@Component
public class IntegrationAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static ObjectMapper mapper;
    private static final String INVALID_TOKEN = "Invalid access token:";

    static {
        mapper = new ObjectMapper();
    }


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseEnum exceptionEnum = ResponseEnum.UNAUTHORIZED;
        if (authException.getMessage().contains(INVALID_TOKEN)) {
            exceptionEnum = ResponseEnum.TOKEN_EXPIRE;
        }
        GlobalResponse responseVO = GlobalResponse.buildFail(exceptionEnum);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            mapper.writeValue(response.getOutputStream(), responseVO);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}
